package com.hopes.bizz.risk.transfer.handler;

import com.hopes.bizz.common.core.util.StringUtils;
import com.hopes.bizz.risk.common.constant.enums.RiskModDictEnum;
import com.hopes.bizz.risk.control.entity.RiskUnitEntity;
import com.hopes.bizz.risk.control.service.RiskUnitService;
import com.hopes.bizz.risk.transfer.bean.bo.RiskDataBo;
import com.hopes.bizz.risk.transfer.bean.dto.RiskUnitDto;
import com.hopes.bizz.risk.transfer.constant.RiskErrorType;
import com.hopes.bizz.risk.transfer.constant.RiskRequestType;
import com.hopes.bizz.risk.transfer.converter.RiskUnitConverter;
import com.hopes.boss.admin.api.resolver.DictResolver;
import com.hopes.boss.common.data.org.OrgContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lyb
 * @version 1.0
 * @description: 风险单元数据处理器
 * @date 2024/2/2 9:36
 */

@Component
@Slf4j
public class RiskUnitDataHandler extends AbstractRiskData<RiskUnitDto> {

    @Resource
    private RiskUnitService riskUnitService;

    @Override
    protected void saveRiskData(RiskUnitDto riskUnitDto, RiskDataBo riskDataBo) {
        // 校验危险源是否存在
        String riskObjectId = DictResolver.getItemValueByLabel(RiskModDictEnum.risk_object_code, riskUnitDto.getHazardCode());
        if (StringUtils.isBlank(riskObjectId)) {
            saveErrorLog(riskUnitDto, riskDataBo, RiskErrorType.HAZ_SOURCE_NOT_FOUND);
            return;
        }
        String uid = riskUnitDto.getId();
        RiskUnitEntity riskUnit = riskUnitService.getByUid(uid);
        RiskUnitEntity riskUnitEntity = RiskUnitConverter.INSTANCE.toEntity(riskUnitDto);
        riskUnitEntity.setRiskObjectId(Long.valueOf(riskObjectId));
        riskUnitEntity.setOrgId(riskDataBo.getOrgId());
        if (Objects.isNull(riskUnit)) {
            riskUnitService.save(riskUnitEntity);
        } else {
            riskUnitEntity.setId(riskUnitEntity.getId());
            riskUnitService.updateById(riskUnitEntity);
        }
    }

    @Override
    public RiskRequestType getRequestType() {
        return RiskRequestType.RISK_UNIT;
    }
}
